package com.example.onlinemarket.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.onlinemarket.R;
import com.example.onlinemarket.adapter.RecyclerViewAdapter;
import com.example.onlinemarket.graphics.GoodInfoDialog;
import com.example.onlinemarket.model.Good;
import com.example.onlinemarket.model.User;
import com.example.onlinemarket.util.ActivityUtil;
import com.example.onlinemarket.util.JSONUtil;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.example.onlinemarket.util.ActivityUtil.goShop;
import static com.example.onlinemarket.util.ActivityUtil.showBigImage;
import static com.example.onlinemarket.util.HttpUtil.addGoodToShoppingCart;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;

public class MainFragment extends Fragment {

    private List<User> shopList;
    private List<Good> goodList;
    private RecyclerView recyclerView;
    private RecyclerViewAdapter adapter;
    private SmartRefreshLayout refreshLayout;
    private LinearLayout tipLayout;

    private com.example.onlinemarket.activity.MainActivity.OnLoadMoreListener onLoadMoreListener;

    public MainFragment() {
        shopList = new ArrayList<>();
        goodList = new ArrayList<>();
    }

    //设置上拉监听器
    public void setOnLoadMoreListener(com.example.onlinemarket.activity.MainActivity.OnLoadMoreListener onLoadMoreListener){
        this.onLoadMoreListener = onLoadMoreListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //初始化组件
    private void initWidgets(View view){
        tipLayout = view.findViewById(R.id.layout_tip);
        recyclerView = view.findViewById(R.id.recycler_view);
        refreshLayout = view.findViewById(R.id.layout_refresh);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = getShopAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(true);//启用上拉加载
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);//不满一页也可以上拉加载
        refreshLayout.setEnableRefresh(false);//关闭刷新
        refreshLayout.setEnableScrollContentWhenLoaded(true);//在加载完成时滚动列表显示新的内容
    }

    //为组件设置事件监听器
    private void setWidgetsListener(){
        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> onLoadMoreListener.onLoadMore());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        initWidgets(view);//初始化组件
        setWidgetsListener();//为组件设置事件监听器


        //陈雪
        new Thread(() -> {
            String responseData = sendHttpRequest("/search/goodAll", "GET",null);
            if(responseData!=null&&!responseData.isEmpty()){
                List<Good> goods = JSONUtil.fromJsons(responseData, new TypeToken<List<Good>>() {}.getType());
                if (goods!=null){
                    Log.e("商品的数据源",goods.toString());
                }
                if(goods.size()>0)
                    updateGoodData(goods, true);
                else
                    showBlankPage();
            }
        }).start();


        return view;
    }

    //获取商品对应适配器
    private RecyclerViewAdapter<Good> getGoodAdapter() {
        if(goodList==null||goodList.isEmpty()){
            refreshLayout.setVisibility(View.GONE);
            tipLayout.setVisibility(View.VISIBLE);
        }else{
            refreshLayout.setVisibility(View.VISIBLE);
            tipLayout.setVisibility(View.GONE);
        }
        return new RecyclerViewAdapter<Good>(getContext(), R.layout.good_item, goodList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.good_item;
            }
            @Override
            public void convert(ViewHolder holder, Good data, int position) {
                //显示商品图片
//                holder.setImage(R.id.good_img, data.getImgPath());
                ImageView  img=holder.getView(R.id.good_img);

                Log.e("数据源",data.getPhoto().toString());
//                 使用 Glide 加载图片
                Glide.with(getActivity())
                        .load(data.getPhoto())
                        .into(img);


                holder.setOnClickListener(R.id.good_img, v -> showBigImage(data.getLocalPath()));
                //显示商品名称
                holder.setText(R.id.good_name, data.getGoodName());
                //显示商品价格
                holder.setText(R.id.good_price, String.valueOf(data.getSellPrice()));
                //点击按钮将商品添加到购物车
                holder.setOnClickListener(R.id.btn_good_item_add_shopping_cart, v -> new Thread(() -> {
                    int goodId = goodList.get(position).getGoodId();
                    addGoodToShoppingCart(goodId);
                }).start());
                holder.setOnClickListener(R.id.layout_good_item, v -> GoodInfoDialog.newInstance(context, goodList.get(position)).show());
            }
        };
    }

    //获取商铺对应适配器
    private RecyclerViewAdapter<User> getShopAdapter() {
        if(shopList==null||shopList.isEmpty()){
            refreshLayout.setVisibility(View.GONE);
            tipLayout.setVisibility(View.VISIBLE);
        }else{
            refreshLayout.setVisibility(View.VISIBLE);
            tipLayout.setVisibility(View.GONE);
        }
        return new RecyclerViewAdapter<User>(getContext(), R.layout.shop_item, shopList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.shop_item;
            }

            @Override
            public void convert(ViewHolder holder, User data, int position) {
                holder.setImage(R.id.shop_img, data.getImgPath());
                holder.setOnClickListener(R.id.shop_img, v -> showBigImage(data.getLocalPath()));
                holder.setText(R.id.shop_name, data.getUserName());
                holder.setText(R.id.tv_shop_item_shop_email, data.getEmail());
                holder.setOnClickListener(R.id.btn_shop_item_enter, v -> goShop(getActivity(), shopList.get(position)));
            }
        };
    }

    //添加或刷新数据
    public void updateShopData(List<User> list, boolean isFullyUpdate){
        if(isFullyUpdate) {//若为完全更新则清空另一列表，同时刷新RecyclerView
            shopList = list;
            goodList.clear();
            Objects.requireNonNull(getActivity()).runOnUiThread(() -> recyclerView.setAdapter(getShopAdapter()));
        }
        else//若不是完全更新则将新获取的数据添加到列表并刷新视图
            shopList.addAll(list);
        Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
            recyclerView.setAdapter(getShopAdapter());
            refreshLayout.finishLoadMore(true);
        });
    }

    //添加或刷新数据
    public void updateGoodData(List<Good> list, boolean isFullyUpdate){
        if(isFullyUpdate) {//若为完全更新则清空另一列表，同时刷新RecyclerView
            goodList = list;
            shopList.clear();
            if (recyclerView!=null){
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> recyclerView.setAdapter(getGoodAdapter()));
            }
        }
        else {//若不是完全更新则将新获取的数据添加到列表并刷新视图
            for(Good good:list){
                boolean isExists = false;
                for(Good item:goodList){
                    isExists = isExists || item.getGoodId().equals(good.getGoodId());
                }
                if(!isExists){
                    good.getGoodImg();
                    goodList.add(good);
                }
            }
            Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                recyclerView.setAdapter(getGoodAdapter());
                refreshLayout.finishLoadMore(true);
            });
        }
        if (refreshLayout==null){
            Log.e("查看组件refreshLayout是否为空","空");
            return;
        }
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setNoMoreData(false);
        refreshLayout.finishLoadMore(true);
    }

    //显示无数据空白页
    public void showBlankPage() {
        goodList.clear();
        shopList.clear();
        tipLayout.setVisibility(View.VISIBLE);
        refreshLayout.setVisibility(View.GONE);
    }
}